<template>
  <div class="page">
    <h2>个体化治疗计划</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/目标/干预搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterStatus" placeholder="全部状态" style="width:160px">
        <el-option label="全部状态" :value="''" />
        <el-option label="进行中" value="active" />
        <el-option label="完成" value="completed" />
        <el-option label="暂停" value="paused" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新建计划</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="140" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="startDate" label="开始日期" width="120" />
      <el-table-column prop="endDate" label="预计结束" width="120" />
      <el-table-column prop="primaryGoal" label="主要目标" />
      <el-table-column prop="responsible" label="负责人" width="120" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status==='completed'? 'success' : row.status==='paused' ? 'warning' : 'info'">{{ statusMap[row.status] }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.id)">查看/编辑</el-button>
          <el-button size="small" type="primary" @click="addProgress(row.id)" style="margin-left:8px">记录进展</el-button>
          <el-button size="small" type="success" @click="markComplete(row.id)" style="margin-left:8px">标为完成</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchSetStatus('active')">批量标记进行中</el-button>
      <el-button @click="batchSetStatus('completed')">批量标记完成</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑治疗计划' : '新建治疗计划'" v-model="showModal" width="720px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄/性别">
          <div style="display:flex;gap:8px">
            <el-input-number v-model="form.age" :min="0" style="width:120px" />
            <el-select v-model="form.gender" style="width:120px">
              <el-option label="男" value="M" />
              <el-option label="女" value="F" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="主要目标">
          <el-input v-model="form.primaryGoal" />
        </el-form-item>
        <el-form-item label="干预措施">
          <el-input v-model="form.interventions" placeholder="例如：认知行为疗法/家庭治疗/药物治疗" />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker v-model="form.startDate" type="date" style="width:200px" />
        </el-form-item>
        <el-form-item label="预计结束">
          <el-date-picker v-model="form.endDate" type="date" style="width:200px" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="form.responsible" />
        </el-form-item>
        <el-form-item label="进度/备注">
          <el-input v-model="form.note" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:160px">
            <el-option label="进行中" value="active" />
            <el-option label="完成" value="completed" />
            <el-option label="暂停" value="paused" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const q = ref('');
const filterStatus = ref('');
const data = ref([]);
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ name:'', age:0, gender:'M', primaryGoal:'', interventions:'', startDate:'', endDate:'', responsible:'', note:'', status:'active' });

const statusMap = { active:'进行中', completed:'完成', paused:'暂停' };

onMounted(()=> load());
function load(){
  data.value = [
    {id:1,name:'小明',age:15,gender:'M',startDate:'2025-09-01',endDate:'2025-12-01',primaryGoal:'减轻社交焦虑',interventions:'CBT+学校辅导',responsible:'张医生',note:'已开展个案工作',status:'active'},
    {id:2,name:'小红',age:16,gender:'F',startDate:'2025-06-01',endDate:'2025-09-01',primaryGoal:'稳定情绪波动',interventions:'药物+心理治疗',responsible:'李医生',note:'复评中',status:'completed'}
  ];
}

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(String(d.name).toLowerCase().includes(qq) || String(d.primaryGoal).toLowerCase().includes(qq) || String(d.interventions).toLowerCase().includes(qq))) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

watch(selectedRows, v=> selectedIds.value = v.map(i=>i.id));
function onSelectionChange(rows){ selectedRows.value = rows; }
function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{ name:'', age:0, gender:'M', primaryGoal:'', interventions:'', startDate:'', endDate:'', responsible:'', note:'', status:'active' }); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.name){ ElMessage.warning('姓名为必填项'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); } else { const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({id:nid}, JSON.parse(JSON.stringify(form)))); } ElMessage.success('保存成功'); showModal.value = false; }

function addProgress(id){ const it = data.value.find(x=>x.id===id); if(!it) return; ElMessage.info('请在计划详情页记录具体进展'); }
function markComplete(id){ const it = data.value.find(x=>x.id===id); if(!it) return; it.status='completed'; ElMessage.success('已标为完成'); }

function getSelectedIds(){ return selectedIds.value.slice(); }
function batchSetStatus(s){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.id)) d.status = s; }); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); selectedIds.value=[]; selectedRows.value=[]; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','name','age','gender','startDate','endDate','primaryGoal','interventions','responsible','note','status'], ...data.value.map(d=>[d.id,d.name,d.age,d.gender,d.startDate,d.endDate,d.primaryGoal,d.interventions,d.responsible,d.note||'',d.status||'']) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='treatment_plans.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>